package sjs.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 
public final class EMF { 
    private static final EntityManagerFactory emfInstance = 
        Persistence.createEntityManagerFactory("transactions-optional"); 
 
    private EMF() {} 
 
    public static EntityManagerFactory get() {
        return emfInstance; 
    }
    public static void save(Object o){
    	EntityManager em=EMF.get().createEntityManager();
	    try{
	    	em.persist(o);
	    //	em.flush();
	    }catch(Exception e){
	    	e.printStackTrace();
	    }finally{
	   // 	em.close();
	    }
    }
    public static void delete(Object o){
    	EntityManager em=EMF.get().createEntityManager();
	    try{
	    	em.remove(o);
	    //	em.flush();
	    }catch(Exception e){
	    	e.printStackTrace();
	    }finally{
	    //	em.close();
	    }
    }
    public static Object findById(Class  c ,Long id){
    	EntityManager em=EMF.get().createEntityManager();
	    try{
	    	return  em.find(c, id);
	    }catch(Exception e){
	    	e.printStackTrace();
	    }finally{
	  //  	 em.close();
	    }
	    return null;
    }
    public static List getListByQl(String ql){
    	EntityManager em=EMF.get().createEntityManager();
    	List resList= null;
	    try{
	    	//if(pm.isClosed())PMF.get().
	    	resList= em.createQuery(ql).getResultList();
	    }catch(Exception e){
	    	e.printStackTrace();
	    }finally{
	    //	em.close();
	    }
    	return resList;
    }
    public static List getAllListByName(String name){
    	EntityManager em=EMF.get().createEntityManager();
    	List resList= null;
	    try{
	    	//if(pm.isClosed())PMF.get().
	    	resList= em.createNamedQuery(name).getResultList();
	    }catch(Exception e){
	    	e.printStackTrace();
	    }finally{
	    	//em.close();
	    }
    	return resList;
    }
}